package com.chcit.mobile.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chcit.custom.view.loader.LoaderStyle;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.custom.view.spinner.DropDownMenu;
import com.chcit.custom.view.text.one.SuperTextView;
import com.chcit.hwmsmobile.edittext.SuperEditText;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.app.utils.TimeDialogUtil;
import com.chcit.mobile.helper.recycler.RecycleViewDivider;
import com.chcit.mobile.mvp.model.entity.BpartnerBean;
import com.chcit.mobile.mvp.model.entity.InventoryPlanBean;
import com.chcit.mobile.mvp.model.entity.Statu;
import com.chcit.mobile.mvp.model.entity.StorageBean;
import com.chcit.mobile.mvp.ui.adapter.GirdDropDownAdapter;
import com.chcit.mobile.mvp.ui.adapter.InventoryPlanAdapter;
import com.chcit.mobile.mvp.ui.adapter.InventoryPlanQueryAdapter;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.base.app.Quick;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.chcit.mobile.di.component.DaggerInventoryPlanQueryComponent;
import com.chcit.mobile.di.module.InventoryPlanQueryModule;
import com.chcit.mobile.mvp.contract.InventoryPlanQueryContract;
import com.chcit.mobile.mvp.presenter.InventoryPlanQueryPresenter;

import com.chcit.mobile.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class InventoryPlanQueryFragment extends ScanFragment<InventoryPlanQueryPresenter> implements InventoryPlanQueryContract.View {

    @BindView(R.id.et_inventory_plan_package_document_no)
    SuperEditText etProductName;
    @BindView(R.id.bt_inventory_plan_query)
    Button btQuery;
    @BindView(R.id.pr_inventory_plan_dropDownMenu)
    DropDownMenu mDropDownMenu;
    @BindView(R.id.lv_inventory_plan_list)
    RecyclerView mRecyclerView;
    protected String type;
    private List<InventoryPlanBean> storageBeans;
    private InventoryPlanQueryAdapter mAdapter;
    private InventoryPlanBean storageBean;
    private int REQUEST_CODE = this.getClass().hashCode();
    private int itemPosition;
    private TextInputEditText tietProductName;
    private TextInputEditText tietLocator;
    private SuperTextView tvDateFrom;
    private SuperTextView tvDateTo;
    private BpartnerBean bpartnerBean;
    private ArrayList<BpartnerBean> bpartners;
    private String headers[] = {"选择货主", "输入商品", "选择日期"};
    public static InventoryPlanQueryFragment newInstance() {
        InventoryPlanQueryFragment fragment = new InventoryPlanQueryFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerInventoryPlanQueryComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .inventoryPlanQueryModule(new InventoryPlanQueryModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_inventory_plan_query, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mCommonToolbar.setTitle("盘点查询");
        mCommonToolbar.getViewByTag(1).setOnClickListener(l -> {
            pop();
            l.setOnClickListener(null);
            if (getActivity() != null) {
                _mActivity.finish();
            }

        });
        initDropDownMenu();
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext,LoaderStyle.BallSpinFadeLoaderIndicator);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
        getActivity().finish();
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        etProductName.setText(barcodeData);
        getData();
    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initRecyclerView();
    }

    private void initRecyclerView() {
        mAdapter = new InventoryPlanQueryAdapter(storageBeans);
        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                itemPosition = position;
                storageBean = (InventoryPlanBean) adapter.getData().get(position);
                startForResult(InventoryPlanFragment.newInstance(storageBean), REQUEST_CODE);
//                CheckBox checkBox = view.findViewById(R.id.box_puchase_select);
//                checkBox.performClick();
            }
        });
        mRecyclerView.setAdapter(mAdapter);

    }
    private void initDropDownMenu() {
        final List<View> popupViews = new ArrayList<>();

        //供应商选择
        final ListView wareView = new ListView(mContext);
        bpartners = new ArrayList<>();
        bpartners.add(new BpartnerBean("", "不限"));

        final GirdDropDownAdapter<BpartnerBean> bpartnerAdapter = new GirdDropDownAdapter<BpartnerBean>(mContext, bpartners);
        wareView.setDividerHeight(0);
        wareView.setAdapter(bpartnerAdapter);
        wareView.setOnItemClickListener((parent, view, position, id) -> {
            bpartnerAdapter.setCheckItem(position);
            bpartnerBean = bpartners.get(position);
            if (position == 0) {
                bpartnerBean = null;
            }
            mDropDownMenu.setTabText(position == 0 ? headers[0] : bpartnerBean.getName());
            mDropDownMenu.closeMenu();
        });

        //日期选择
        final View dateView = getLayoutInflater().inflate(R.layout.pop_date, null);
        tvDateFrom = dateView.findViewById(R.id.pop_date_from);
        tvDateTo = dateView.findViewById(R.id.pop_date_drive);

        tvDateFrom.getCenterTextView().setText(TimeDialogUtil.getBeforeDay(1));
        tvDateFrom.setCenterString(TimeDialogUtil.getBeforeDay(1));
        tvDateFrom.setOnClickListener(v -> TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->tvDateFrom.setCenterString(s), 6));
        tvDateTo.setOnClickListener(v -> TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->tvDateTo.setCenterString(s), 0));
        tvDateTo.setRightImageViewClickListener(l->{
            tvDateTo.setCenterString("");
        });
        tvDateFrom.setRightImageViewClickListener(l->{
            tvDateFrom.setCenterString("");
        });
        TextView ok = dateView.findViewById(R.id.ok);
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = tvDateFrom.getCenterString()+"\\n"+ tvDateTo.getCenterString();
                mDropDownMenu.setTabText(text.isEmpty() ? headers[1] : text);
                mDropDownMenu.closeMenu();
            }
        });

        //商品选择
        final View constellationView = getLayoutInflater().inflate(R.layout.pop_inventory, null);
        tietProductName = constellationView.findViewById(R.id.constellation);//厂家
        tietLocator = constellationView.findViewById(R.id.pop_inventory_locator);
        tietLocator.setVisibility(View.GONE);
        TextView tvConfirm = constellationView.findViewById(R.id.ok);
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = tietProductName.getText().toString();
                mDropDownMenu.setTabText(text.isEmpty() ? headers[1] : text);
                mDropDownMenu.closeMenu();
                onViewClicked(btQuery);
            }
        });

        popupViews.add(wareView);
        popupViews.add(constellationView);
        popupViews.add(dateView);
        final TextView contentView = new TextView(getContext());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        contentView.setText("");
        //contentView.setBackgroundColor(getResources().getColor(R.color.gray));
        contentView.setGravity(Gravity.CENTER);
        contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        final List<String> list = Arrays.asList(headers);
        mDropDownMenu.setDropDownMenu(list, popupViews, contentView);
        tvDateTo.setRightImageViewClickListener(l->{
            tvDateTo.setCenterString("");
        });
        tvDateFrom.setRightImageViewClickListener(l->{
            tvDateFrom.setCenterString("");
        });
        mPresenter.getBpartners(bpartnerBeans -> {
            bpartners.addAll(bpartnerBeans);
            bpartnerAdapter.notifyDataSetChanged();
        });

    }

    @OnClick({R.id.bt_inventory_plan_query})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_inventory_plan_query:
                mAdapter.getData().clear();
                getData();
                break;
        }
    }

    private void getData() {
        JSONObject data = new JSONObject();
               /* start:0
                    limit:25
                    documentNo:10000
                    productName:1548_713
                    validation: o.Docstatus = 'DR'
                    appSessionID:1542677744838.12*/
        data.put("start", 0);
        data.put("limit", 25);
        data.put("showLot", true);

        if (!etProductName.getText().toString().isEmpty()) {
            data.put("documentNo", etProductName.getText().toString());
        }
        if (!tietProductName.getText().toString().isEmpty()) {
          data.put("productName", tietProductName.getText().toString());
      }
                /*if (!tietLocator.getText().toString().isEmpty()) {
                    data.put("manufacturer", tietLocator.getText().toString());
                }*/
        if (bpartnerBean != null) {
            data.put("orgID", bpartnerBean.getId());
        }
        if (!tvDateFrom.getCenterTextView().getText().toString().isEmpty()) {
            data.put("dateFrom", tvDateFrom.getCenterTextView().getText().toString());
        }
        if (!tvDateTo.getCenterTextView().getText().toString().isEmpty()) {
            data.put("dateTo", tvDateTo.getCenterTextView().getText().toString());
        }
        mPresenter.getData(data, list -> {

            mAdapter.addData(list);
        });
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            mAdapter.getData().clear();
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            mCommonToolbar.setTitle("盘点查询");
            mCommonToolbar.getViewByTag(1).setOnClickListener(l -> {
                pop();
                l.setOnClickListener(null);
                if (getActivity() != null) {
                    _mActivity.finish();
                }

            });
        }
    }
}
